package com.css.zfzx.data.primary.qhRiskLevelMapPointPG.service.impl;

import com.css.zfzx.data.common.Constant;
import com.css.zfzx.data.common.GenerateSiteCodeUtil;
import com.css.zfzx.data.common.ProvinceCityAreaUtil;
import com.css.zfzx.data.common.ResolveGeometryUtil;
import com.css.zfzx.data.postgresql.fxqhPriorityPG.repository.entity.FxqhPriorityPostgresqlEntity;
import com.css.zfzx.data.postgresql.pgReconciliation.repository.PgReconciliationNativeRepository;
import com.css.zfzx.data.postgresql.qhRiskLevelMapPointPG.repository.QhRiskLevelMapPointRepository;
import com.css.zfzx.data.postgresql.qhRiskLevelMapPointPG.repository.entity.QhRiskLevelMapPointPostgresqlEntity;
import com.css.zfzx.data.primary.base.division.service.BaseDivisionService;
import com.css.zfzx.data.primary.base.repository.SuperRepository;
import com.css.zfzx.data.primary.base.vo.ProxyVO4;
import com.css.zfzx.data.primary.base.vo.ProxyVO9;
import com.css.zfzx.data.primary.qhRiskLevelMapPointPG.repository.QhRiskLevelMapPointPGNativeRepository;
import com.css.zfzx.data.primary.qhRiskLevelMapPointPG.repository.entity.QhRiskLevelMapPointPGEntity;
import com.css.zfzx.data.primary.qhRiskLevelMapPointPG.service.QhRiskLevelMapPointPGService;
import com.css.zfzx.data.thirdary.jgReconciliation.repository.entity.SjtgfJghshYjSjdzbEntity;
import com.css.zfzx.data.thirdary.jgReconciliation.service.ReconciliationService;
import com.css.zfzx.data.util.DateUtil;
import com.css.zfzx.data.util.GeometryUtil;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author lxg
 * @date 2020-11-10
 */
@Log4j2
@Service
public class QhRiskLevelMapPointPGServiceImpl implements QhRiskLevelMapPointPGService {
    private final QhRiskLevelMapPointPGNativeRepository nativeRepository;
    private final QhRiskLevelMapPointRepository repository;
    private final PgReconciliationNativeRepository jgNativeRepository;
    private final ReconciliationService reconciliationService;
    @Autowired
    SuperRepository superRepository;
    @Autowired
    BaseDivisionService baseDivisionService;
    @Autowired
    public QhRiskLevelMapPointPGServiceImpl(QhRiskLevelMapPointPGNativeRepository nativeRepository, QhRiskLevelMapPointRepository repository, PgReconciliationNativeRepository jgNativeRepository, ReconciliationService reconciliationService) {
        this.nativeRepository = nativeRepository;
        this.repository = repository;
        this.jgNativeRepository = jgNativeRepository;
        this.reconciliationService = reconciliationService;
    }

    public static List<String> pioneerType1 =new ArrayList<>();
    @PostConstruct
    public void init() {
        pioneerType1 = baseDivisionService.findPioneerType1();
        pioneerType1.add("130709");
        pioneerType1.add("110119");
    }
    /**
     * 新增数据不包含修改
     *
     * @return
     */
    @Override
    public void findDataCreate() {
        LocalDateTime createTime = repository.findCreateTime();
        //查询新增数据
        //List<String> strings = nativeRepository.findAreaCreate(createTime);
        Map<String, String> errorMap = new HashMap<>();
        int sum1 = 0;
        int sum2 = 0;
        int flag = 0;
        String startCode = null;
        List<String> strings=Arrays.asList("崇礼区","延庆区","滨海新区","平山县","孝义市","扎赉特旗","凌海市","延吉市","通河县","徐汇区","兴化市","苍南县","相山区","同安区","兴国县","沾化区","博爱县","公安县","长沙县","从化区","全州县","万宁市","合川区","康定市","仁怀市","盈江县","江达县","神木市","东乡族自治县","格尔木市","沙坡头区","库车市");
        //List<String> strings=Arrays.asList("崇礼区","延庆区");
        for (String area : strings) {
            List<QhRiskLevelMapPointPGEntity> entities = nativeRepository.findEntityCreate(createTime,area);
            if (entities.size() == 0) {
                System.out.println("qh_risk_level_map_point:时间" + new Date() + ",添加查询了数据：" + entities.size() + " 条");
                continue;
            }
            sum1=sum1+entities.size();
            List<QhRiskLevelMapPointPostgresqlEntity> saveList = new ArrayList<>();
            for (QhRiskLevelMapPointPGEntity entity : entities) {
                String uuid = entity.getUuid();
                String code = ProvinceCityAreaUtil.getCode(entity.getProvince(), entity.getCity(), entity.getArea());
                if (code == null) {
                    errorMap.put(uuid, "区划编码获取失败!");
                    break;
                }
                // if (!pioneerType1.contains(code)) {
                //     String cityCode = code.substring(0, 4) + "00";
                //     if (!pioneerType1.contains(cityCode)) {
                //         errorMap.put(entity.getProvince()+entity.getCity()+entity.getArea(), "不属于11个试点县!");
                //         break;
                //     }
                // }
                QhRiskLevelMapPointPostgresqlEntity postgresEntity = new QhRiskLevelMapPointPostgresqlEntity();
                BeanUtils.copyProperties(entity, postgresEntity);
                postgresEntity.setFxpcDataidSjgl(entity.getUuid());

                // double[] doubles =new double[2];
                // if (entity.getGeoPoint()!=null) {
                //     doubles = ResolveGeometryUtil.bytesToOnePoint(entity.getGeoPoint().getBytes());
                // }else {
                //     doubles = ResolveGeometryUtil.bytesToMultipoint(entity.getGeoMultipoint());
                // }
                // String point = "POINT (" + doubles[0] + " " + doubles[1] + ")";
                String point = null;
                if (entity.getGeoPoint()!=null&&StringUtils.isNotEmpty(entity.getGeoPoint())) {
                    point=entity.getGeoPoint();
                }else {
                    point=entity.getGeoMultipoint();
                }
                try{
                    Geometry geometry = GeometryUtil.setRecArea(point);
                    postgresEntity.setExtends1(geometry);
                }catch (Exception e){
                    e.printStackTrace();
                    errorMap.put(entity.getUuid(),"空间数据:{}"+point+" 异常!");
                }

                String oldSitCode = null;
                if (flag == 0) {
                    flag++;
                    oldSitCode = repository.getGenerateSiteCode();
                } else {
                    oldSitCode = startCode;
                }
                String generateSiteCode = GenerateSiteCodeUtil.generateSiteCode(code, oldSitCode, "");
                startCode = generateSiteCode;
                postgresEntity.setFxpcDcdxbmSjgl(generateSiteCode);
                //根据名称获取行政编码

                if (!StringUtils.isEmpty(entity.getProvince()) && StringUtils.isEmpty(entity.getCity())) {
                    postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                }
                if (!StringUtils.isEmpty(entity.getCity()) && StringUtils.isEmpty(entity.getArea())) {
                    postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                    postgresEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                }
                if (!StringUtils.isEmpty(entity.getArea())) {
                    postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                    postgresEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                    postgresEntity.setFxpcXzqhbmcSjgl(code);
                }
                //标识数据的当前状态，如果是新增数据，该字段为I；
                // 如果数据被更新过，该字段为U；如果数据被删除，该字段为D。
                postgresEntity.setFxpcSjztSjgl("I");
                //将创建时间转化成字符串形式
                if (entity.getCreateTime() != null) {
                    postgresEntity.setFxpcCreatetimeSjgl(DateUtil.getContainsHMS(entity.getCreateTime()));
                }
                //统一都是默认040
                postgresEntity.setFxpcSshySjgl("040");
                //日期分片
                postgresEntity.setFxpcRqfpSjgl(DateUtil.getNotContainsHMS(new Date()));
                //批次号
                postgresEntity.setFxpcPchSjgl(DateUtil.getNotContainsHMS(new Date()));
                //审核流程状态
                postgresEntity.setFxpcShlcztSjgl(Constant.SHLCZT_ZZSH);
                //审核状态
                postgresEntity.setFxpcShztSjgl(Constant.SHZT_TG);
                saveList.add(postgresEntity);
            }
            long startIn = System.currentTimeMillis();
            int iterable = jgNativeRepository.batchSave1(saveList);
            long endIn = System.currentTimeMillis();
            sum2 = sum2 + iterable;
            System.out.println("qh_risk_level_map_point"+area+"县:时间" + new Date() + ",插入数据：" + saveList.size() +
                    " 条,失败：" + (entities.size() - saveList.size()) + " 条,用时  " + (endIn - startIn));
            update(iterable, saveList);
        }
        if (errorMap.size() != 0) {
            log.error(errorMap);
        }
        System.out.println("qh_risk_level_map_point:时间" + new Date() + ",插入数据：" +sum2 + " 条,一共  " + sum1);
        SjtgfJghshYjSjdzbEntity sjtgfJghshYjSjdzbEntity = new SjtgfJghshYjSjdzbEntity();
        sjtgfJghshYjSjdzbEntity.setBmc("qh_risk_level_map_point");
        sjtgfJghshYjSjdzbEntity.setSjts(sum2);
        sjtgfJghshYjSjdzbEntity.setLch(Integer.valueOf("101"));
        reconciliationService.saveReconciliation(sjtgfJghshYjSjdzbEntity);
    }
    private void update(int iterable,List<QhRiskLevelMapPointPostgresqlEntity> saveList){
        List<ProxyVO9> proxyVOs=new ArrayList<>();
        for (int i=0;i<iterable;i++) {
            QhRiskLevelMapPointPostgresqlEntity pgEntity = saveList.get(i);
            ProxyVO9 proxyVO=new ProxyVO9();
            proxyVO.setUuid(pgEntity.getUuid());
            ////proxyVO.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            proxyVO.setIsReportPg("1");
            proxyVOs.add(proxyVO);
        }
        superRepository.batchUpdate(proxyVOs);
    }
    @Override
    public void findDataUpdate() {
        LocalDateTime updateTime = repository.findUpdateTime();
        //查询新增数据
        //List<String> strings=nativeRepository.findAreaUpdate(updateTime);
        Map<String, String> errorMap = new HashMap<>();
        int sum1 = 0;
        int sum2 = 0;
        int flag = 0;
        String startCode = null;
        //List<String> strings=Arrays.asList("崇礼区","延庆区");
        //List<String> strings=Arrays.asList("江达县");
        List<String> strings=Arrays.asList("崇礼区","延庆区","滨海新区","平山县","孝义市","扎赉特旗","凌海市","延吉市","通河县","徐汇区","兴化市","苍南县","相山区","同安区","兴国县","沾化区","博爱县","公安县","长沙县","从化区","全州县","万宁市","合川区","康定市","仁怀市","盈江县","江达县","神木市","东乡族自治县","格尔木市","沙坡头区","库车市");
        for (String area : strings) {
            List<QhRiskLevelMapPointPGEntity> entities = nativeRepository.findEntityUpdate(updateTime,area);
            if (entities.size() == 0) {
                System.out.println("qh_risk_level_map_point:时间" + new Date() + ",修改查询了数据：" + entities.size() + " 条");
                continue;
            }
            sum1=sum1+entities.size();
            List<QhRiskLevelMapPointPostgresqlEntity> saveList = new ArrayList<>();
            for (QhRiskLevelMapPointPGEntity entity : entities) {
                String uuid = entity.getUuid();
                String code = ProvinceCityAreaUtil.getCode(entity.getProvince(), entity.getCity(), entity.getArea());
                if (code == null) {
                    errorMap.put(uuid, "区划编码获取失败!");
                    break;
                }
                // if (!pioneerType1.contains(code)) {
                //     String cityCode = code.substring(0, 4) + "00";
                //     if (!pioneerType1.contains(cityCode)) {
                //         errorMap.put(entity.getProvince()+entity.getCity()+entity.getArea(), "不属于11个试点县!");
                //         break;
                //     }
                // }
                QhRiskLevelMapPointPostgresqlEntity postgresEntity = new QhRiskLevelMapPointPostgresqlEntity();
                BeanUtils.copyProperties(entity, postgresEntity);
                postgresEntity.setFxpcDataidSjgl(entity.getUuid());
                // double[] doubles =new double[2];
                // if (entity.getGeoPoint()!=null) {
                //     doubles = ResolveGeometryUtil.bytesToOnePoint(entity.getGeoPoint().getBytes());
                // }else {
                //     doubles = ResolveGeometryUtil.bytesToMultipoint(entity.getGeoMultipoint());
                // }
                // String point = "POINT (" + doubles[0] + " " + doubles[1] + ")";
                String point = null;
                if (entity.getGeoPoint()!=null&&StringUtils.isNotEmpty(entity.getGeoPoint())) {
                    point=entity.getGeoPoint();
                }else {
                    point=entity.getGeoMultipoint();
                }
                try{
                    Geometry geometry = GeometryUtil.setRecArea(point);
                    postgresEntity.setExtends1(geometry);
                }catch (Exception e){
                    e.printStackTrace();
                    errorMap.put(entity.getUuid(),"空间数据:{}"+point+" 异常!");
                }

                String oldSitCode = null;
                if (flag == 0) {
                    flag++;
                    oldSitCode = repository.getGenerateSiteCode();
                } else {
                    oldSitCode = startCode;
                }
                String generateSiteCode = GenerateSiteCodeUtil.generateSiteCode(code, oldSitCode, "");
                startCode = generateSiteCode;
                postgresEntity.setFxpcDcdxbmSjgl(generateSiteCode);
                //根据名称获取行政编码

                if (!StringUtils.isEmpty(entity.getProvince()) && StringUtils.isEmpty(entity.getCity())) {
                    postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                }
                if (!StringUtils.isEmpty(entity.getCity()) && StringUtils.isEmpty(entity.getArea())) {
                    postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                    postgresEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                }
                if (!StringUtils.isEmpty(entity.getArea())) {
                    postgresEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                    postgresEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                    postgresEntity.setFxpcXzqhbmcSjgl(code);
                }
                //标识数据的当前状态，如果是新增数据，该字段为I；
                // 如果数据被更新过，该字段为U；如果数据被删除，该字段为D。
                if (entity.getIsValid().equals("0")) {
                    postgresEntity.setFxpcSjztSjgl("D");
                } else {
                    postgresEntity.setFxpcSjztSjgl("U");
                }
                //将创建时间转化成字符串形式
                if (entity.getCreateTime() != null) {
                    postgresEntity.setFxpcCreatetimeSjgl(DateUtil.getContainsHMS(entity.getCreateTime()));
                }
                if (entity.getUpdateTime() != null) {
                    postgresEntity.setFxpcUpdatetimeSjgl(DateUtil.getContainsHMS(entity.getUpdateTime()));
                }
                //统一都是默认040
                postgresEntity.setFxpcSshySjgl("040");
                //日期分片
                postgresEntity.setFxpcRqfpSjgl(DateUtil.getNotContainsHMS(new Date()));
                //批次号
                postgresEntity.setFxpcPchSjgl(DateUtil.getNotContainsHMS(new Date()));
                //审核流程状态
                postgresEntity.setFxpcShlcztSjgl(Constant.SHLCZT_ZZSH);
                //审核状态
                postgresEntity.setFxpcShztSjgl(Constant.SHZT_TG);
                saveList.add(postgresEntity);
            }
            long startIn = System.currentTimeMillis();
            int iterable = jgNativeRepository.batchUpdate1(saveList);
            long endIn = System.currentTimeMillis();
            sum2 = sum2 + iterable;
            System.out.println("qh_risk_level_map_point"+area+"县:时间" + new Date() + ",修改数据：" + saveList.size() +
                    " 条,失败：" + (entities.size() - saveList.size()) + " 条,用时  " + (endIn - startIn));
            update(iterable, saveList);
        }
        if (errorMap.size() != 0) {
            log.error(errorMap);
        }
        System.out.println("qh_risk_level_map_point:时间" + new Date() + ",修改数据：" +sum2 + " 条,一共  " + sum1);
        SjtgfJghshYjSjdzbEntity sjtgfJghshYjSjdzbEntity = new SjtgfJghshYjSjdzbEntity();
        sjtgfJghshYjSjdzbEntity.setBmc("qh_risk_level_map_point");
        sjtgfJghshYjSjdzbEntity.setSjts(sum2);
        sjtgfJghshYjSjdzbEntity.setLch(Integer.valueOf("201"));
        reconciliationService.saveReconciliation(sjtgfJghshYjSjdzbEntity);
    }
}
